package com.ch8.demo02;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;

/**
 * @author woldier
 * @version 1.0
 * @description 测试自定义aqs独享lock
 * @date 2023/6/7 12:20
 **/
@Slf4j(topic = "c.Tread")
public class TestAQSLock {
    public static void main(String[] args) {
        TestAQS lock = new TestAQS();
        final Cake cake = new Cake();
        Condition cakeCondition = lock.newCondition();
        /*吃蛋糕线程*/
        new Thread(()->{
            lock.lock();
            if(!cake.isHasCake()) {
                log.debug("没蛋糕,进入阻塞队列");
                try {
                    cakeCondition.await();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            try{
                log.debug("吃蛋糕");
                TimeUnit.SECONDS.sleep(2);
                cake.setHasCake(false);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                lock.unlock();
            }
        },"t1").start();

        /*做蛋糕线程*/
        new Thread(()->{
            lock.lock();
            if(cake.isHasCake()) {
                log.debug("蛋糕还没吃,进入阻塞队列");
            }
            try{
                log.debug("做蛋糕");
                TimeUnit.SECONDS.sleep(2);
                cake.setHasCake(true);

                cakeCondition.signal();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                lock.unlock();
            }
        },"t2").start();
    }

}
